package netty.discard;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

//当有客户端连接时，发送一条消息，并且关闭连接
public class TimeServerHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        ByteBuf buffer = ctx.alloc().buffer(4);//32为整数，至少分配一个4字节的buf
//        buffer.writeInt((int) (System.currentTimeMillis() / 1000L+ 2208988800L));
//        ChannelFuture f = ctx.writeAndFlush(buffer);//数据发送是异步的，需要数据发送完再关闭连接
        ChannelFuture f = ctx.writeAndFlush(new UnixTime());
        System.out.println("write data...");
        f.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                assert f == future;
                ctx.close();
                System.out.println("connect closed!!");
            }
        });


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //不同异常可能有不同实现，此处暂且关闭连接
        cause.printStackTrace();
        ctx.close();
    }
}
